package Servlet;


import BaseQuery.FoodQuery;
import Bean.Food;
import Server.IFoodServe;
import Server.impl.FoodServe;
import Utils.IOUtils;
import Utils.JdbcUtils;
import Utils.JsonUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import vo.ResultBean;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/food")
public class FoodServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		IFoodServe foodServe=new FoodServe();
		ResultBean resultBean=null;
		String what=req.getParameter("what");
		try {
			if ("save".equals(what)) {
				System.out.println("添加或修改餐品");
				//读取输入流中的json字符串(请求体的内容)
				String jsonStr = IOUtils.readStr(req.getInputStream());
				//将json字符串转成food对象
				Food food = JsonUtils.jsonStrToObj(jsonStr,"yyyy-MM-dd", Food.class);
				//判断food中有没有主键
				if(food.getFoodId()==null){
					resultBean = foodServe.add(food);
				}else{
					resultBean = foodServe.update(food);
				}

			}  else if ("del".equals(what)) {
				System.out.println("删除操作");
				String  id=req.getParameter("id");
				resultBean =foodServe.delete(Integer.parseInt(id));

			} else if ("getById".equals(what)) {
				System.out.println("根据id查询操作");
				String  id=req.getParameter("id");
				resultBean=foodServe.getById(Integer.parseInt(id));
			} else if("page".equals(what)) {
				System.out.println("分页搜索餐品");
				String jsonStr = IOUtils.readStr(req.getInputStream());
				FoodQuery foodQuery= JsonUtils.jsonStrToObj(jsonStr, "yyyy-MM-dd",FoodQuery.class);
				//这是将一个请求体的内容换成一个查询的条件。
				resultBean= foodServe.getByPage(foodQuery);
				System.out.println("----------------------------------");
			} else if("batchDel".equals(what)) {
				System.out.println("进入批量删除的操作");
				String jsonStr = IOUtils.readStr(req.getInputStream());
				JSONArray jsonArray=JSONObject.parseArray(jsonStr);
				List<Integer> ids=jsonArray.toJavaList(Integer.class);
				System.out.println("json转集合"+ids);
				resultBean=foodServe.batchDel(ids);
			}
			else {
				System.out.println("无服务");
				resultBean = ResultBean.ERROR(500, "无此项服务，请重新输入正确服务命令");
			}
		}catch (Exception e) {
			e.printStackTrace();
			resultBean=ResultBean.ERROR(e.getMessage());
		}
		//将resultBean转成json字符串响应即可
		String resultStr=JSONObject.toJSONString(resultBean);
		resp.getWriter().write(resultStr);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req,resp);
	}
}
